/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jse;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 *
 * @author WangShuai
 */
public class GetBytesTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //JVM默认的编码取决于操作系统平台，如中文系统默认为GBK
        //可以通过指定JVM的file.encoding参数来设定默认字符集
        System.out.println("The Default Charset is : " + Charset.defaultCharset().displayName());
        
        String s = "中国";
        //Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 
        //使用系统默认字符集将字符串编码成字节数组
        byte[] b1 = s.getBytes();
        System.out.println("GetBytes Use Default Charset : ");
        for(byte b : b1){
            System.out.print(b);
        }
        System.out.println("");
        //Constructs a new String by decoding the specified array of bytes using the platform's default charset.
        //使用平台默认字符集解码字节数组构造字符串
        System.out.println(new String(b1));     //中国 
        //此时默认字符集为UTF-8
        System.out.println(new String(b1,"utf-8")); //中国
        //由于字节数组使用UTF-8编码生成，使用其他字符集解码字节数组会出现乱码
        System.out.println(new String(b1,"GBK"));  //乱码
        System.out.println(new String(b1,"iso8859-1"));  //乱码
        
        //使用GBK将字符串编码成字节数组
        byte[] b2 = s.getBytes("GBK");
        System.out.println("GetBytes Use GBK : ");
        for(byte b : b2){
            System.out.print(b);
        }
        System.out.println("");
        System.out.println(new String(b2,"GBK"));  
    }
}
